package com.example.demo.generator.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.sun.mail.util.MailSSLSocketFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@RestController
@Api(tags = "邮件接口")
public class EmailController {

    private static final String from="lyllsgz@163.com";//163邮件的账号
    private static final String host = "smtp.163.com";
    private static final String password = "DZLLTVUAPNFMKGHJ";//163邮箱的授权码，下面会详细描述怎么开通【注意，不是密码】
    @GetMapping("send163")
    @ApiOperation("163邮件发送接口")
    public R send163(@RequestParam("addressee")String addressee,@RequestParam("content")String content){
        Properties prop = new Properties();
        prop.setProperty("mail.host", host);
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密，否则会失败
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);

//这一句必须加上，不然会报错，我的博客中有提到，不知道的，可以去看 :https://blog.csdn.net/QinTao9961220/article/details/108917422
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            Session session = Session.getInstance(prop);
            /* prop.put("mail.smtp.ssl.enable", true);*/
            Transport ts = session.getTransport();
            // 连接邮件服务器：邮箱类型，帐号，授权码代替密码（更安全）
            ts.connect(host,from, password);//后面的字符是授权码，用qq密码反正我是失败了（用自己的，别用我的，这个号是我瞎编的，为了。。。。）
            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            // 指明邮件的发件人
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(addressee));
            // 邮件的标题
            message.setSubject("验证码");
            // 邮件的文本内容
            /*int code=100000+(int)(899999*Math.random());
            System.out.println(code);*/
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            return R.ok("success");
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("error");
        }
    }
}
